import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartbeatClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            if (event.state() == IdleState.READER_IDLE) {
                type = "read idle";
                IMessage iMessage = new IMessage();
                iMessage.setType(MessageTypeEnum.PING);
                iMessage.setBody("PING");
                ctx.writeAndFlush(iMessage);
            } else if (event.state() == IdleState.WRITER_IDLE) {
                // 如果当前服务在指定时间内没有写入消息到管道，则关闭当前管道
                type = "write idle";
                ctx.close();
            } else if (event.state() == IdleState.ALL_IDLE) {
                type = "all idle";
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
